﻿using Castle.DynamicProxy;
using Publicuse.Entity;
using Publicuse.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Autofac
{
    /// <summary>
    /// 缓存管理
    /// </summary>
    public class CacheInterceptor : IInterceptor
    {
        private object[] input;

        public void Intercept(IInvocation invocation)
        {
            this.input = invocation.Arguments;
            var businessType = (BusinessType)input[0];
            if (businessType == BusinessType.querycache)
            {
                CommonQuery query = this.input[2] as CommonQuery;
                DataCacheUtil.GetDataCacheUtil.GetData(query.tableName, out var result);
                if (result == null)
                {
                    invocation.Proceed();
                    var invokeResult = invocation.ReturnValue as CommonResult;
                    DataCacheUtil.GetDataCacheUtil.AddData(query.tableName, invokeResult);
                }
                else
                {
                    if (result.count > 0)
                    {
                        invocation.ReturnValue = result;
                    }
                    else
                    {
                        invocation.Proceed();
                        var invokeResult = invocation.ReturnValue as CommonResult;
                        DataCacheUtil.GetDataCacheUtil.AddData(query.tableName, invokeResult);
                    }
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
